//==================客户端======================
const dateKit = require("./util/dateKit");
const dataKit = require("./util/dataKit");
const util = require("./util/util")
const businessService = require("./util/businessService")


/**
* 商户登录（保存token）
*/
exports.businessLogin = async (context) => {
  const { userNick } = context.data;
  const { openId, accessToken } = context;
  if (!userNick) {
    return { code: 500, msg: "userNick是必须的" };
  }
  if (!accessToken) {
    return { code: 500, msg: "accessToken是必须的" };
  }

  let merchant = await businessService.getMerchantByOpenId(context, openId);
  if (!merchant) {
    //首次登陆
    merchant = {
      openId: openId,
      createTime: dateKit.getCurrentDateTime()
    };
  }
  merchant.accessToken = accessToken;
  merchant.loginTime = dateKit.getCurrentDateTime();
  merchant.userNick = userNick;
  const result = await dataKit.insertOrUpdate(context, "merchant", merchant);
  return { code: 200, msg: "登录成功", data: accessToken };
}



/**
 * 查看奖品
 * @param {*} context 
 */
exports.lookPrize = async (context) => {

  const { state } = context.data;
  const { pageNo } = context.data;
  let pNo = (pageNo - 1) * 10;
  if(pageNo == null){
    return {code:500,msg:"页码不能为空"}
  }
  var result = {};
  if (state != null) {
    result = await context.cloud.db.collection('task_log').find(
      { 
        state: state 
      },{
        limit:10,
        skip:pNo
      }

    );
  } else {
    result = await context.cloud.db.collection('task_log').find({},{
        limit:10,
        skip:pNo
    });
  }

  return {code:1,msg:"返回数据为",data:result};
}

/**
 * 输入快递单号
 */

exports.input = async (context) => {
  const { u_openId, courier_number, cdkey } = context.data;
  const result = await dataKit.update(context, 'task_log', {
    open_id: u_openId,
    cdkey: cdkey
  }, {
    courier_number: courier_number,
    state: 1
  })
  if (!result) {
    return { code: -1, msg: "输入快递单号失败" }
  }
  return { code: 1, msg: "输入快递单号成功" }
}

/**
 * 通过兑换码查询
 */

exports.check = async (context) => {
  const { cdkey } = context.data;
  let user = await dataKit.findOne(context, "task_log", { cdkey: cdkey });
  return user;
}

